<template>
  <div>
    <el-page-header @back="goBack" class="mt-[10px] ml-[10px] text-[12px]">
      <template #content>
        <span class="text-[12px] font-400 mr-3 c-blueGray">
          {{ formData.processName }}
        </span>
      </template>
      <template #extra>
        <div class="flex items-center">
          <el-button
            type="primary"
            v-show="!isReadonly"
            :loading="loading"
            @click="handleSubmit"
            class="save_btn"
            >保 存</el-button
          >
        </div>
      </template>
    </el-page-header>
    <div class="app-container workManageSetting">
      <el-tabs v-model="activeTab" type="border-card" class="demo-tabs">
        <el-tab-pane name="tab1">
          <template #label>
            <span class="custom-tabs-label">
              <el-icon><calendar /></el-icon>
              <span>工序信息</span>
            </span>
          </template>
          <div>
            <div class="header">
              <span class="title">基础信息</span>
            </div>
            <el-form
              ref="formRef"
              :model="formData"
              :rules="rules"
              label-width="130px"
              class="execure_require_form"
            >
              <div style="width: 100%; max-width: 1400px">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="生产序号" prop="workSequence">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.workSequence"
                        placeholder="请输入"
                        clearable
                      />
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{ formData.workSequence || " " }}</span
                      >
                    </el-form-item>
                  </el-col>
                  <el-col :span="16">
                    <el-form-item label="">
                      <el-checkbox-group v-model="formData.checkList">
                        <el-checkbox label="首工序" :disabled="isReadonly" />
                        <el-checkbox label="中间工序" :disabled="isReadonly" />
                        <el-checkbox label="末工序" :disabled="isReadonly" />
                      </el-checkbox-group>
                    </el-form-item>
                    <!-- 位置类型 -->
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="工序" prop="processName">
                      <select-routing-progress-input
                        v-show="!isReadonly"
                        width="100%"
                        :isMultiple="false"
                        placeholder="请选择工序"
                        :showSelectDevice="selectRouteProgressData"
                        @get-device="getRouteProgress"
                      />
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{ formData.processName || " " }}</span
                      >
                    </el-form-item></el-col
                  >

                  <el-col :span="8">
                    <el-form-item label="班产" prop="tactYield">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.tactYield"
                        placeholder="请输入"
                        clearable
                      />
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{ formData.tactYield || " " }}</span
                      >
                    </el-form-item></el-col
                  >
                  <!-- <el-col :span="2" /> -->
                  <el-col :span="8">
                    <el-form-item label="工序类别" prop="processType">
                      <el-select
                        v-show="!isReadonly"
                        v-model="formData.processType"
                        placeholder="请选择"
                        clearable
                      >
                        <el-option
                          v-for="item in useDictionary('ProcessType')"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value * 1"
                        />
                      </el-select>
                      <span
                        class="w-[192px] border_b_black"
                        v-show="isReadonly"
                        >{{
                          useDictionary("ProcessType", formData.processType)
                        }}</span
                      >
                    </el-form-item></el-col
                  >
                </el-row>

                <el-row>
                  <el-col :span="8"
                    ><el-form-item label="生产节拍" prop="tactTime">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.tactTime"
                        placeholder="请输入"
                      >
                        <template #append>秒</template>
                      </el-input>
                      <span class="w-[192px] border_b_black" v-show="isReadonly"
                        >{{ formData.tactTime }}秒</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="基础加工数量" prop="baseQuantity">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.baseQuantity"
                        placeholder="请输入"
                        clearable
                      />
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{ formData.baseQuantity || " " }}</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="基础加工单位" prop="baseQuantityUnit">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.baseQuantityUnit"
                        placeholder="请输入"
                        clearable
                      />
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{ formData.baseQuantityUnit || " " }}</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="机器工时" prop="machineTime">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.machineTime"
                        placeholder="请输入"
                        clearable
                      >
                        <template #append>秒</template>
                      </el-input>
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{
                          formData.machineTime
                            ? `${formData.machineTime}秒`
                            : formData.machineTime == "0"
                            ? `0秒`
                            : ""
                        }}</span
                      >
                    </el-form-item></el-col
                  >

                  <el-col :span="8">
                    <el-form-item label="劳动工时" prop="laborTime">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.laborTime"
                        placeholder="请输入"
                        clearable
                      >
                        <template #append>秒</template>
                      </el-input>
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{
                          formData.laborTime
                            ? `${formData.laborTime}秒`
                            : formData.laborTime == "0"
                            ? `0秒`
                            : ""
                        }}</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="移入工时" prop="inboundTime">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.inboundTime"
                        placeholder="请输入"
                        clearable
                      >
                        <template #append>秒</template>
                      </el-input>
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{
                          formData.inboundTime
                            ? `${formData.inboundTime}秒`
                            : formData.inboundTime == "0"
                            ? `0秒`
                            : ""
                        }}</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="移出工时" prop="outboundTime">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.outboundTime"
                        placeholder="请输入"
                        clearable
                      >
                        <template #append>秒</template>
                      </el-input>
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{
                          formData.outboundTime
                            ? `${formData.outboundTime}秒`
                            : formData.outboundTime == "0"
                            ? `0秒`
                            : ""
                        }}</span
                      >
                    </el-form-item></el-col
                  >

                  <el-col :span="8">
                    <el-form-item label="准备工时" prop="prepareTime">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.prepareTime"
                        placeholder="请输入"
                        clearable
                      >
                        <template #append>秒</template>
                      </el-input>
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{
                          formData.prepareTime
                            ? `${formData.prepareTime}秒`
                            : formData.prepareTime == "0"
                            ? `0秒`
                            : ""
                        }}</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="等待工时" prop="waitTime">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.waitTime"
                        placeholder="请输入"
                        clearable
                      >
                        <template #append>秒</template>
                      </el-input>
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{
                          formData.waitTime
                            ? `${formData.waitTime}秒`
                            : formData.waitTime == "0"
                            ? `0秒`
                            : ""
                        }}</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="换型时间" prop="transferTime">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.transferTime"
                        placeholder="请输入"
                        clearable
                      >
                        <template #append>秒</template>
                      </el-input>
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{
                          formData.transferTime
                            ? `${formData.transferTime}秒`
                            : formData.transferTime == "0"
                            ? `0秒`
                            : ""
                        }}</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="总工时" prop="totalTime">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.totalTime"
                        placeholder="请输入"
                        clearable
                      >
                        <template #append>秒</template>
                      </el-input>
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{
                          formData.totalTime
                            ? `${formData.totalTime}秒`
                            : formData.totalTime == "0"
                            ? `0秒`
                            : ""
                        }}</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="合计成本" prop="totalCost">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.totalCost"
                        placeholder="请输入"
                        clearable
                      >
                        <template #append>元</template>
                      </el-input>
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{
                          formData.totalCost
                            ? `${formData.totalCost}元`
                            : formData.totalCost == "0"
                            ? `0元`
                            : ""
                        }}</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="委外供应商" prop="supplierId">
                      <el-select
                        v-show="!isReadonly"
                        v-model="formData.supplierId"
                        clearable
                        placeholder="请选择"
                        @change="supplierChange"
                        filterable
                      >
                        <el-option
                          v-for="item in supplierList"
                          :key="item.id"
                          :label="`${item.partnerCode}-${item.partnerName}`"
                          :value="item.id"
                        />
                      </el-select>
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{
                          formData.supplierId
                            ? `${formData.supplierCode}-${formData.supplierName}`
                            : ""
                        }}</span
                      >
                    </el-form-item></el-col
                  >

                  <el-col :span="8">
                    <el-form-item label="加工人数" prop="workerQuantity">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.workerQuantity"
                        placeholder="请输入"
                        clearable
                      />
                      <span
                        class="w-[100%] border_b_black"
                        v-show="isReadonly"
                        >{{ formData.workerQuantity }}</span
                      >
                    </el-form-item></el-col
                  >
                  <el-col :span="8">
                    <el-form-item label="关键工序" prop="keyProcess">
                      <el-radio-group v-model="formData.keyProcess">
                        <el-radio
                          v-for="item in useDictionary('YesNo')"
                          :key="item.value"
                          :label="item.value * 1"
                          :disabled="isReadonly"
                        >
                          {{ item.label }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item></el-col
                  >

                  <el-col :span="8">
                    <el-form-item label="主工序" prop="primaryProcess">
                      <el-radio-group v-model="formData.primaryProcess">
                        <el-radio
                          v-for="item in useDictionary('YesNo')"
                          :key="item.value"
                          :label="item.value * 1"
                          :disabled="isReadonly"
                        >
                          {{ item.label }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item
                      label="自动进入下一位置"
                      prop="transferToNext"
                    >
                      <el-radio-group v-model="formData.transferToNext">
                        <el-radio
                          v-for="item in useDictionary('YesNo')"
                          :key="item.value"
                          :label="item.value * 1"
                          :disabled="isReadonly"
                        >
                          {{ item.label }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <div
                      style="
                        color: red;
                        font-size: 13px;
                        margin-left: 15px;
                        margin-top: -15px;
                        height: 40px;
                      "
                    >
                      如果下道序是并行工序，自动无效，不自动流转人为处理。
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="是否报工" prop="report">
                      <el-radio-group v-model="formData.report">
                        <el-radio
                          v-for="item in useDictionary('YesNo')"
                          :key="item.value"
                          :label="item.value * 1"
                          :disabled="isReadonly"
                        >
                          {{ item.label }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="是否启用" prop="enabled">
                      <el-radio-group v-model="formData.enabled">
                        <el-radio
                          v-for="item in useDictionary('Enabled')"
                          :key="item.value"
                          :label="item.value * 1"
                          :disabled="isReadonly"
                        >
                          {{ item.label }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="备注" prop="remarks">
                      <el-input
                        v-show="!isReadonly"
                        v-model="formData.remarks"
                        placeholder="暂无备注"
                        type="textarea"
                        show-word-limit
                        :maxlength="255"
                        :autosize="{ minRows: 4, maxRows: 5 }"
                      />
                      <span v-show="isReadonly" class="border_b_black">{{
                        formData.remarks
                      }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
              <div class="planTable">
                <div class="header">
                  <span class="title">设备列表</span>
                  <el-button
                    v-show="!isReadonly"
                    type="success"
                    plain
                    small
                    @click="handleStep"
                    >新 增</el-button
                  >
                </div>

                <el-table
                  :data="formData.processEquipment"
                  style="width: 100%"
                  :key="Math.random"
                  :border="true"
                >
                  <el-table-column
                    label="设备顺序号"
                    fixed="left"
                    show-overflow-tooltip
                    :align="!isReadonly ? 'left' : 'center'"
                  >
                    <template #default="{ $index, row }">
                      <!-- 分行校验的关键在于:prop="'processEquipment.' + $index + '.name'" -->
                      <el-form-item
                        v-show="!isReadonly"
                        :prop="'processEquipment.' + $index + '.workSequence'"
                        :rules="rules.equSequence"
                        label-width="0px"
                        class="center-input"
                      >
                        <el-input
                          v-model="row.workSequence"
                          placeholder="请输入"
                          clearable
                          small
                        />
                      </el-form-item>
                      <span v-show="isReadonly">{{ row.workSequence }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="设备编号"
                    props="equipmentCode"
                    show-overflow-tooltip
                    :align="!isReadonly ? 'left' : 'center'"
                  >
                    <template #default="{ $index, row }">
                      <!-- 分行校验的关键在于:prop="'processEquipment.' + $index + '.name'" -->
                      <el-form-item
                        :prop="'processEquipment.' + $index + '.equipmentCode'"
                        :rules="rules.equipmentCode"
                        label-width="0px"
                        v-show="!isReadonly"
                      >
                        <el-select
                          style="width: 100%"
                          v-model="row.equipmentId"
                          placeholder="请选择设备"
                          clearable
                          @change="(e) => changEquipment(e, $index)"
                        >
                          <el-option
                            v-for="item in equipmentList"
                            :label="`${item.equipmentCode}`"
                            :value="`${item.equipmentId}`"
                          />
                        </el-select>
                      </el-form-item>
                      <span v-show="isReadonly">{{ row.equipmentCode }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="设备名称"
                    props="equipmentName"
                    show-overflow-tooltip
                  >
                    <template #default="{ $index, row }">
                      <!-- 分行校验的关键在于:prop="'processEquipment.' + $index + '.name'" -->
                      <!-- <el-form-item
                        v-show="!isReadonly"
                        :prop="'processEquipment.' + $index + '.equipmentName'"
                        :rules="rules.equipmentName"
                        label-width="0px"
                      >
                        <el-input
                          v-model="row.equipmentName"
                          placeholder="请输入"
                          clearable

                          small
                        />
                      </el-form-item> -->
                      <span>{{ row.equipmentName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="班产"
                    props="tactYield"
                    show-overflow-tooltip
                  >
                    <template #default="{ $index, row }">
                      <!-- 分行校验的关键在于:prop="'processEquipment.' + $index + '.name'" -->
                      <el-form-item
                        v-show="!isReadonly"
                        :prop="'processEquipment.' + $index + '.tactYield'"
                        :rules="rules.tactYield"
                        label-width="0px"
                      >
                        <el-input
                          v-model="row.tactYield"
                          placeholder="请输入"
                          clearable
                          small
                        />
                      </el-form-item>
                      <span v-show="isReadonly">{{ row.tactYield }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" align="center" label="操作">
                    <template #default="scope">
                      <el-button
                        type="danger"
                        link
                        class="mt-[-10px]"
                        @click.stop="handleDelete(scope.$index)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane name="tab2"
          ><template #label>
            <span class="custom-tabs-label">
              <el-icon><Document /></el-icon>
              <span>工艺文件</span>
            </span>
          </template>
          <UploadFileList
            :files="formData.files"
            @update-files="updateFormFiles"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<!-- 手动挂载左侧菜单高亮 -->
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  beforeRouteEnter(to, from, next) {
    to.meta.defaultActive = "/mes/mesRouting/list";
    if (!to.query.id) {
      to.meta.title = "新建工序";
    } else {
      to.meta.title = "编辑工序";
    }
    if (to.query.isReadonly == 1) {
      to.meta.title = "查看工序";
    }
    next();
  },
});
</script>

<script setup lang="ts">
import request from "@/utils/request";
import { useRoute } from "vue-router";
import router from "@/router";
import { validateZeroNumber } from "@/utils/commonHooks";
import UploadFileList from "../components/uploadFileList/index.vue";
import { Calendar, Document } from "@element-plus/icons-vue";
import { useDictionary } from "@/utils/useTable";
import { getSupplierList, getCrewList } from "@/utils/commonData";
import { useTagsViewStore, TagView } from "@/store/modules/tagsView";
const tagsViewStore = useTagsViewStore();

defineOptions({
  name: "MESMESROUTINGADDPROGRESS",
  inheritAttrs: false,
});

const route: any = useRoute();

const isReadonly = ref(route.query.isReadonly == 1 ? true : false);

// 位置选择
function handleChangeCheck(value: string[]) {
  formData.firstProcess = "";
  formData.middleProcess = "";
  formData.lastProcess = "";
  value.map((item: string) => {
    if (item === "首工序") {
      formData.firstProcess = "1";
    } else if (item === "中间工序") {
      formData.middleProcess = "1";
    } else if (item === "末工序") {
      formData.lastProcess = "1";
    }
  });
}

// 供应商选择
function supplierChange(e) {
  if (e) {
    const current = supplierList.value.filter((item: any) => item.id === e);
    formData.supplierCode = current[0].partnerCode || "";
    formData.supplierId = current[0].id || "";
    formData.supplierName = current[0].partnerName || "";
  } else {
    formData.supplierCode = "";
    formData.supplierId = "";
    formData.supplierName = "";
  }
}

// 班组选择
function selectCrewCode(data: string, index: number) {
  if (data) {
    const current = crewList.value.filter((e: any) => e.crewCode === data);
    formData.processEquipment[index].crewCode = current[0].crewCode || "";
    formData.processEquipment[index].crewId = current[0].id || "";
  } else {
    formData.processEquipment[index].crewCode = "";
    formData.processEquipment[index].crewId = "";
  }
}

// 获取设备选择信息
function getDevice(Ids: string[], Objects: any, index: number) {
  if (Objects.length) {
    formData.processEquipment[index].equipmentCode = Objects[0].equipCode || "";
    formData.processEquipment[index].equipmentId = Objects[0].id || "";
    formData.processEquipment[index].equipmentName = Objects[0].equipName || "";
  } else {
    formData.processEquipment[index].equipmentCode = "";
    formData.processEquipment[index].equipmentId = "";
    formData.processEquipment[index].equipmentName = "";
  }
}

// 回显/设置设备信息
const selectRouteProgressData: any = ref([]);
// 获取设备选择信息
function getRouteProgress(Ids: string[], Objects: any) {
  formData.processEquipment = [];
  if (Objects.length) {
    console.log(111, Objects);

    formData.processId = Objects[0].id;
    formData.processCode = Objects[0].processCode || "";
    formData.processName = Objects[0].processName || "";
    formData.plantId = Objects[0].plantId;
    formData.plantCode = Objects[0].plantCode;
    formData.plantName = Objects[0].plantName;
    formData.workCenterId = Objects[0].workCenterId || "";
    formData.workCenterName = Objects[0].workCenterName || "";
    formData.workCenterCode = Objects[0].workCenterCode || "";
  } else {
    formData.plantId = "";
    formData.plantCode = "";
    formData.plantName = "";
    formData.processId = "";
    formData.processCode = "";
    formData.processName = "";
    formData.workCenterId = "";
    formData.workCenterName = "";
    formData.workCenterCode = "";
  }
}

const changEquipment = (e, index) => {
  if (e) {
    equipmentList.value.forEach((item) => {
      if (item.equipmentId == e) {
        formData.processEquipment[index].equipmentCode = item.equipmentCode;
        formData.processEquipment[index].equipmentName = item.equipmentName;
      }
    });
  } else {
    formData.processEquipment[index].equipmentId = "";
    formData.processEquipment[index].equipmentCode = "";
    formData.processEquipment[index].equipmentName = "";
  }
};

// 一个工步
const onePlan = {
  // id: "",
  // workSequence: "", // 工步顺序号
  // processStepName: "", // 工步名称
  // equipmentCode: "", // 设备编号
  // equipmentId: "", // 设备id
  // equipmentName: "", // 设备名称
  // crewCode: "", // 班组编号
  // crewId: "", // 班组id
  // machineTime: "", // 机器工时
  // laborTime: "", // 劳动工时
  // inboundTime: "", // 移入工时
  // outboundTime: "", // 移出工时
  // prepareTime: "", // 准备工时
  // waitTime: "", // 等待工时
  // totalTime: "", // 总工时
  // transferTime: "", // 换型时间
  id: "",
  mesRoutingProcess: "",
  routingId: "",
  routingCode: "",
  processId: "",
  processCode: "",
  processName: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  workCenterId: "",
  workCenterCode: "",
  equipmentId: "",
  equipmentCode: "",
  equipmentName: "",
  tactYield: "",
  workSequence: "",
};

/** 添加设备 */
function handleStep() {
  if (formData.processId != "") {
    formData.processEquipment.push(JSON.parse(JSON.stringify(onePlan)));
    getEquipmentList(formData.processId);
  } else {
    ElMessage({
      message: "请先选择工序",
      type: "warning",
    });
  }
}

// 根据工序获取设备列表
const equipmentList = ref([]);
const getEquipmentList = async (processId: any) => {
  await request({
    url: "/mes/mesprocessequipment/getList",
    method: "post",
    data: { processId: processId },
  }).then((res) => {
    if (res.code == 200) {
      equipmentList.value = res.data;
      console.log(equipmentList.value);
    }
  });
};

/** 删除工步 */
const handleDelete = (index: any) => {
  formData.processEquipment.splice(index, 1);
};

// 监听当前路由 页面滚到顶部
watch(
  () => router.currentRoute.value,
  (newValue: any) => {
    nextTick(() => {
      document
        .getElementsByClassName("app-main")[0]
        .scrollTo({ top: 0, behavior: "smooth" });
    });
  },
  { immediate: true }
);

/** 定义form信息 */
// 校验重复的设备
const equRepeatCheck = (rule: any, value: any, callback: any) => {
  if (value) {
    const details = formData.processEquipment;
    var findCnt = 0;
    for (let i = 0; i < details.length; i++) {
      const element = details[i];
      if (element.equipmentCode === value) {
        console.log(element.equipmentCode, value);

        findCnt++;
        console.log(findCnt);
      }
    }
    if (findCnt > 1) {
      return callback(new Error("此设备已录入"));
    } else {
      callback();
    }
  } else {
    callback(new Error("请选择设备"));
  }
};
// 校验序号不能为0
const workSequenceCheck = (rule: any, value: any, callback: any) => {
  if (/^\d{1,3}?$/.test(value)) {
    //验证正整数和0的正则
    return true;
  } else {
    callback(new Error("请输入大于0的整数"));
  }
};
// 校验大于0的数字
const tactYieldCheck = (rule: any, value: any, callback: any) => {
  if (/^\d{1,8}?$/.test(value)) {
    //验证正整数和0的正则
    return true;
  } else {
    callback(new Error("请输入大于0的整数"));
  }
};
// 小数校验
function validator1(rule, value, callback: (a?: any) => {}) {
  if (!value) {
    //先判断空可以过
    // callback(new Error("请输入2位整数3位小数"));
    return true;
  } else {
    if (/^\d{1,8}(\.\d{0,9})?$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入小数"));
    }
  }
}
const rules: any = reactive({
  processStepName: [
    { required: true, message: "请输入", trigger: "blur" },
    { max: 50, message: "不能超过50个字符", trigger: "blur" },
  ],
  equipmentCode: [
    {
      required: true,
      trigger: "change",
      validator: equRepeatCheck,
    },
  ],
  crewCode: [{ required: true, message: "请选择", trigger: "change" }],
  processName: [{ required: true, message: "请选择", trigger: "change" }],
  processType: [{ required: true, message: "请选择", trigger: "change" }],
  tactYield: [
    {
      required: true,
      trigger: "blur",
      validator: tactYieldCheck,
    },
  ],
  workSequence: [
    { required: true, message: "请输入生产序号", trigger: "blur" },
    { pattern: /^[1-9]\d*$/, message: "请输入大于0的整数", trigger: "blur" },
  ],
  equSequence: [
    {
      required: true,

      trigger: "blur",
      validator: workSequenceCheck,
    },
    // { pattern: /^[1-9]\d*$/, message: "请输入大于0的整数", trigger: "blur" },
  ],
  tactTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
    { required: true, message: "请输入生产节拍", trigger: "blur" },
    { pattern: /^[1-9]\d*$/, message: "请输入大于0的整数", trigger: "blur" },
  ],
  workerQuantity: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  baseQuantity: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  machineTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  laborTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  inboundTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  outboundTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  prepareTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  transferTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  waitTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  totalTime: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  totalCost: [
    {
      validator: validateZeroNumber,
      trigger: "blur",
    },
  ],
  remarks: [
    { message: "请输入备注", trigger: "blur" },
    { max: 255, message: "备注不能超过255个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm); // 表单ref

// 初始化表单值
const initForm = {
  routingId: route.query.routingId,
  routingCode: route.query.routingCode,
  remarks: "",
  id: "",
  tactTime: "",
  workSequence: "",
  processCode: "",
  processId: "",
  processName: "",
  workCenterId: "",
  workCenterName: "",
  workCenterCode: "",
  processType: "",
  baseQuantity: "",
  baseQuantityUnit: "",
  keyProcess: 1,
  primaryProcess: 1,
  workerQuantity: "",
  machineTime: "",
  laborTime: "",
  inboundTime: "",
  outboundTime: "",
  prepareTime: "",
  waitTime: "",
  transferTime: "",
  totalTime: "",
  totalCost: "",
  supplierCode: "",
  supplierName: "",
  supplierId: "",
  transferToNext: 1,
  report: 1,
  enabled: 1,
  firstProcess: "",
  middleProcess: "",
  lastProcess: "",
  checkList: [],
  processEquipment: [],
  files: [],
  tactYield: "",
};

let formData = reactive(JSON.parse(JSON.stringify(initForm)));

// 文件更新
function updateFormFiles(val: []) {
  formData.files = val;
}

const loading = ref(false);
const activeTab = ref("tab1");
/** 保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      // 工作更新状态
      handleChangeCheck(formData.checkList);
      formData.routingCode = route.query.routingCode;
      loading.value = true;
      await request({
        url: "/mes/mesroutingprocess/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`保存成功`);
      tagsViewStore.delView(route).then((res: any) => {
        router.replace({
          name: "MESMESROUTINGPROGRESS",
          query: { id: route.query.routingId },
        });
      });
    } else {
      activeTab.value = "tab1";
      ElMessage.error("请完善基础信息");
    }
  });
}

// 编辑查看获取详情
async function getTaskDetail() {
  const { data } = await request({
    url: `/mes/mesroutingprocess/get/${route.query.id}`,
    method: "get",
  });
  const {
    remarks,
    id,
    processType,
    workSequence,
    processCode,
    processId,
    processName,
    workCenterId,
    workCenterName,
    workCenterCode,
    ProcessType,
    baseQuantity,
    baseQuantityUnit,
    keyProcess,
    primaryProcess,
    workerQuantity,
    machineTime,
    laborTime,
    inboundTime,
    outboundTime,
    prepareTime,
    waitTime,
    transferTime,
    totalTime,
    totalCost,
    supplierCode,
    supplierName,
    supplierId,
    transferToNext,
    report,
    enabled,
    firstProcess,
    middleProcess,
    lastProcess,
    processEquipment,
    tactTime,
    files,
    tactYield,
  } = data;
  Object.assign(formData, {
    ...data,
    remarks,
    id,
    workSequence,
    processCode,
    processId,
    processName,
    workCenterId,
    workCenterName,
    workCenterCode,
    ProcessType,
    baseQuantity,
    baseQuantityUnit,
    keyProcess,
    primaryProcess,
    workerQuantity,
    machineTime,
    laborTime,
    inboundTime,
    outboundTime,
    prepareTime,
    waitTime,
    transferTime,
    totalTime,
    totalCost,
    supplierCode,
    supplierName,
    supplierId,
    transferToNext,
    report,
    enabled,
    firstProcess,
    middleProcess,
    lastProcess,
    processType,
    tactTime,
    tactYield,
    processEquipment: processEquipment ?? [],
    files: files ?? [],
  });
  getEquList(id);
  getEquipmentList(processId);

  // 位置信息处理
  formData.checkList = [];
  if (firstProcess) {
    formData.checkList.push("首工序");
  }
  if (middleProcess) {
    formData.checkList.push("中间工序");
  }
  if (lastProcess) {
    formData.checkList.push("末工序");
  }
  // 工序处理
  selectRouteProgressData.value = [
    {
      processCode,
      processName,
      workCenterId,
      workCenterName,
      workCenterCode,
      id: processId,
    },
  ];
}
// 编辑时回显
const getEquList = async (id) => {
  const { data } = await request({
    url: `/mes/mesroutingprocessequipment/getList`,
    method: "post",
    data: {
      mesRoutingProcess: id,
    },
  });
  if (data) {
    formData.processEquipment = data;
    console.log(111, data);
  }
};
// 返回
const goBack = () => {
  router.push({
    name: "MESMESROUTINGPROGRESS",
    query: { id: route.query.routingId },
  });
};

const supplierList: any = ref(); // 委外供应商
const crewList: any = ref(); // 班组编号

// 当前页面被激活时触发
onActivated(async () => {
  window.scrollTo(0, 0);
  activeTab.value = "tab1";
  route.query?.id && getTaskDetail();
  supplierList.value = (await getSupplierList(route.query?.plantId)) || [];
  // supplierList.value = [
  //   {
  //     id: "6523232323",
  //     partnerCode: "5656GHGH",
  //     partnerName: "56供应商",
  //   },
  //   {
  //     id: "6523232323555",
  //     partnerCode: "AAAA5656GHGH",
  //     partnerName: "A供应商",
  //   },
  // ];
  crewList.value = (await getCrewList(route.query?.plantId)) || [];
});
</script>
<style lang="scss" scoped>
@import url("./execute-work-requirement.scss");
.border_b_black {
  border-bottom: 1px solid #e4e7ed;
  min-height: 30px;
  padding-left: 3px;
}
.el-select {
  width: 100%;
}
</style>
